<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 技术月报 -->
    <div  ref="rollScroll" :style="{height: 'calc(100vh - 175px)'}" class="rollScroll">
      <a-form-model 
      ref="ruleForm"
      :model="form"
      id="ruleForm"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="月报基础信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="''">
          </custom-form>
        </a-card>
        <a-card :bordered="false" id="approvalTable" ref="approvalTable">
          <div :class="windowScrollFlag?'monthly-anchor marginAnchor':'monthly-anchor'">
             <div class="anchor-tab" v-for="(item,index) in navTabArr" :key='item.anchorId' :class="index===curIndex?'active':''">
               <p  @click="goAnchor(item.anchorId,index)">{{item.name}}</p>
             </div>
          </div>
          <title-name title="方案审批情况" style="margin-top:50px"></title-name>
          <div>
              <h3 class="updateSummary-h3">当月施工方案电子审批数量对比</h3>
             <approval-table :tableData="approvalTableData"></approval-table>
             <div class="notification" style="margin-top:50px">
                <h3 class="updateSummary-h3">当月施组、AB类施工方案报审通报</h3>
                <notification-table :tableData="notificationTableData"></notification-table>
             </div>
              <div class="notification" style="margin-top:50px">
                <h3 class="updateSummary-h3">当月施工方案回退通报（包括施组、ABCD方案）</h3>
                <fallback-table :tableData="fallbackTableData"></fallback-table>
             </div>
          </div>
        </a-card>
        <a-card :bordered="false" id="planModify">
          <title-name title="方案修改和实施情况"></title-name>
          <div>
             <plan-modify-table :tableData="planModifyData"></plan-modify-table>
          </div>
        </a-card>
        <a-card :bordered="false"  id="professionalProject">
          <title-name title="专业工程施工方案讲评情况"></title-name>
          <div>
                <h3 class="updateSummary-h3">当月专业工程讲评情况</h3>
                <month-project :tableData="monthProjectData"></month-project>
            </div>
            <div>
                <h3 class="updateSummary-h3" style="margin-top:50px">下月专业工程讲评计划</h3>
                <next-month-project :tableData="nextMonthProjectData"></next-month-project>
            </div>
        </a-card>
         <a-card :bordered="false"  id="optimize">
          <title-name title="双优化工作管理"></title-name>
           <div>
                <h3 class="updateSummary-h3">双优化立项情况汇总表（年初累计）</h3>
                <optimize-summary-table :tableData="totalCountData"></optimize-summary-table>
            </div>
            <div>
                <h3 class="updateSummary-h3" style="margin-top:50px">双优化电子审批明细表(本月审批通过)</h3>
                <optimize-approval :tableData="detailCountData"></optimize-approval>
            </div>
            <div>
                <h3 class="updateSummary-h3" style="margin-top:50px">双优化实施完成情况汇总表(年初累计)</h3>
                <optimze-complete-table :tableData="completeCountData"></optimze-complete-table>
            </div>
            <div>
                <h3 class="updateSummary-h3" style="margin-top:50px">双优化验收情况汇总表(年初累计)</h3>
                <acceptance-table :tableData="acceptanceCountData"></acceptance-table>
            </div>
            <div>
                <h3 class="updateSummary-h3" style="margin-top:50px">双优化未实施情况(当月计划实施未实施统计)</h3>
                <optimize-unfinished :tableData="optimizeUnfinishedData"></optimize-unfinished>
            </div>
        </a-card>
        <a-card :bordered="false"  id="specification">
          <title-name title="标准规范管理（年初累计）"></title-name>
          <div>
              <specification-table :tableData="specificationData"></specification-table>
          </div>
        </a-card>
        <a-card :bordered="false" id="workArrangement"> 
          <title-name title="下月工作安排"></title-name>
           <div>
                <work-arrangement :tableData="workArrangementData"></work-arrangement>
           </div>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top">
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
    </div>
     
  </base-breadcrumb>
</template>

<script>
import { getNextMonthProject,getMonthProject,getOptimizeUnfinished,getSpecification,
getWorkArrangement,getCountDetail,queryProgramAppListenerListData,getProgramTotal,getTechnicalCurrentMonthAbReport,getTechnicalCurrentMonthRollbackReport} from '@/api/technical/summary' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import ApprovalTable from './components/approvalTable'
import NotificationTable from './components/notificationTable'
import FallbackTable from './components/fallbackTable'
import PlanModifyTable from './components/planModifyTable'
import MonthProject from './components/monthProject'
import NextMonthProject from './components/nextMonthProject'
import OptimizeSummaryTable from './components/optimizeSummaryTable'
import OptimizeApproval from './components/optimizeApproval'
import OptimzeCompleteTable from './components/optimzeCompleteTable'
import AcceptanceTable from './components/acceptanceTable'
import OptimizeUnfinished from './components/optimizeUnfinished'
import SpecificationTable from './components/specificationTable'
import WorkArrangement from './components/workArrangement'
import { summaryMixin } from "./components/mergeCell";
export default {
  mixins:[summaryMixin], //混入文件
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    ApprovalTable,
    NotificationTable,
    FallbackTable,
    PlanModifyTable,
    MonthProject,
    NextMonthProject,
    OptimizeSummaryTable,
    OptimizeApproval,
    OptimzeCompleteTable,
    AcceptanceTable,
    OptimizeUnfinished,
    SpecificationTable,
    WorkArrangement
  },
  data() {
    return { 
      loading: false, // 加载控件
      form: {}, // 表单
      month: '',
      curIndex:0,
      windowScrollFlag:false,
      rightScrollHeight:0,
      navTabArr:[
         {name:'方案审批情况',anchorId:'approvalTable',},
         {name:'方案修改和实施情况',anchorId:'planModify',},
         {name:'专业工程施工方案讲评情况',anchorId:'professionalProject',},
         {name:'双优化工作管理',anchorId:'optimize',},
         {name:'标准规范管理',anchorId:'specification',},
         {name:'下月工作安排',anchorId:'workArrangement',}
      ],
      approvalTableData1:[],
      newTableData:[],
      monthProjectData:[],  //当月专业工程讲评情况
      nextMonthProjectData:[], //下月专业工程讲评计划
      optimizeUnfinishedData:[], //统计双优化未实施计划表
      specificationData:[], //标准规范管理（年初累计）
      workArrangementData:[], //下月工作安排
      alectronicTableData:[],    //当月施工方案电子审批数量对比
      totalCountData:[], //双优化立项情况汇总表
      detailCountData:[], //双优化电子审批明细表
      completeCountData:[], //-双优化实施完成情况汇总表
      acceptanceCountData:[], //双优化验收情况汇总表
      planModifyData:[],  //方案修改和实施情况
      approvalTableData: [], //当月施工方案电子审批数量对比
      notificationTableData:[], //当月施组、AB类施工方案报审通报
      fallbackTableData:[], //当月施工方案回退通报（包括施组、ABCD方案）
      init: false, // 初始化控件

    }
  },
  async mounted() {
      let screeHeight = document.body.clientHeight - 140; 
        this.$nextTick(() => {
            this.rightScrollHeight = screeHeight + 'px'
        })
    // window.addEventListener('scroll', this.handleScroll, true);  // 监听（绑定）滚轮滚动事件
      this.rollScroll = this.$refs.rollScroll
      var $this = this
      // 监听这个dom的scroll事件
       this.rollScroll.onscroll  = (e) => {
        $this.handleScroll(e)
      }
    this.$route.meta.title = '技术月报 查看'
     if(this.month){
       this.form.month = this.month;
      await this.getDetailData();
     }
  },
  computed: {
    formList() {
      return [{keyName: 'month',type: 'BaseInput',disabled: true,label: '月份'},]
    }
  },
  methods: {
    getIdOffsttTop(id){
      return this.$el.querySelector(id).offsetTop;
    },
    handleScroll(e){
      let approvalTable = this.getIdOffsttTop('#approvalTable'),
      planModify = this.getIdOffsttTop('#planModify'),
      professionalProject = this.getIdOffsttTop('#professionalProject'),
      optimize = this.getIdOffsttTop('#optimize'),  
      specification = this.getIdOffsttTop('#specification'),
      workArrangement = this.getIdOffsttTop('#workArrangement'),
      windowScroll = e.target.scrollTop + 52;
      if(windowScroll>=approvalTable && windowScroll<=planModify){
        this.curIndex = 0
      }else if(windowScroll>planModify && windowScroll<=professionalProject){
        this.curIndex = 1
      }else if(windowScroll>professionalProject && windowScroll<=optimize){
        this.curIndex = 2
      }else if(windowScroll>optimize && windowScroll<=specification-200){
        this.curIndex = 3
      }else if(windowScroll>specification-200 && windowScroll<=workArrangement){
        this.curIndex = 4
      }else if(windowScroll>workArrangement){
        this.curIndex = 5
      }
       this.windowScrollFlag = windowScroll > 52;
   },
  goAnchor(id,index) {
    // this.curIndex = index;
      const anchorEle = document.querySelector(`#${id}`);
      if (!!anchorEle ) {
        anchorEle.scrollIntoView({behavior: "smooth", block: "start", inline: "start"})
      }
   },

  isFloat(n){
    return parseInt(n) < parseFloat(n)
  },
  combinedFn(data,isTotal){   //合计
    //isTotal去掉自身加入的数据
    if(isTotal){
       data = data.filter(item=>item.projectName!==isTotal);
    }
    if(data.length>0){
      let res = data.reduce((result, next)=>{
      if(!result) result = {}
      Object.keys(next).forEach((key)=>{
        //数值类型
        if(typeof next[key] == 'number'){
          result[key] = (result[key]?result[key]:0) + next[key]
        }
      })
      return result
     });
     Object.keys(res).forEach((key) => {  
       if(this.isFloat(res[key])){  //是小数的值，保留两位
         res[key] = res[key].toFixed(2)
       }
     });
      let sjyh = 0,fayh=0;
     if(isTotal){  //对双优化电子审批明细表(本月审批通过)特殊处理
        if(data.length){
            sjyh = data.filter((item)=>item.optTypeName==='设计优化') || [];
            fayh = data.filter((item)=>item.optTypeName==='方案优化') || [];
           }
          res.doubleOptName = data?.length || 0;  
          res.optTypeName = `${sjyh.length}/${fayh.length}`;
     }
     return res;
    }
   },
   totalFn(data){  //小合计对双优化电子审批明细表(本月审批通过)小合计
     let newData = this.$clone(data);
    if(data.length>0){
        data.map((item,index)=>{
        let res = item.origin.reduce((result, next)=>{
        if(!result) result = {}
        Object.keys(next).forEach((key)=>{
          //数值类型
          if(typeof next[key] == 'number'){
            result[key] = (result[key]?result[key]:0) + next[key]
          }
   
        })
        return result
      });
      Object.keys(res).forEach((key) => {  
        if(this.isFloat(res[key])){  //是小数的值，保留两位
          res[key] = res[key].toFixed(2)
        }
        });
        if(res){
          res.planTime=null;  
          res.projectName = "合计";
          newData[index].origin.push(res)
          res.doubleOptName = newData[index].origin.length-1 || 0;
          let neworigin = this.$clone(newData[index].origin) || [];
          if(neworigin.length>0){
            neworigin.pop();
          }
          let sjyh = 0,fayh=0;
          if(neworigin.length){
             sjyh = neworigin.filter((item)=>item.optTypeName==='设计优化') || [];
             fayh = neworigin.filter((item)=>item.optTypeName==='方案优化') || [];
          }
          res.optTypeName = `${sjyh.length}/${fayh.length}`;
        }
        })
    }
      return newData;
   },
 handlerDatas(arr){    //id相同的数据合并在一个数组
    let afterData = []
    arr.forEach(item => {
      let flag = afterData.find(item1 => item1.branchComId === item.branchComId)
      if (!flag) {
        afterData.push({
          branchComId: item.branchComId,
          origin: [item]
        })
      } else {
        flag.origin.push(item)
      }
    })
   return afterData;
    },
   async getDetailData(){
     try {
        this.loading = true;
        const p1 = await getMonthProject({   //专业工程施工方案讲评情况 - 当月专业工程讲评情况
         queryMonth:this.month
        });
        const p2 = await getNextMonthProject({   //专业工程施工方案讲评情况 - 下月专业工程讲评计划
         queryMonth:this.month
        });
        const p3 = await getOptimizeUnfinished({ //双优化未实施情况(当月计划实施未实施统计)
          monthCreate:this.month
        });  
        const p4 = await getSpecification({     //标准规范管理（年初累计）
          monthCreate:this.month
        });
        const p5 = await getWorkArrangement({  //下月工作安排
           nextMonth:this.month
        });
        const p6 = await getCountDetail({  //双优化相关统计API
          month:`${this.month}-01`
        });
        const p7 =await queryProgramAppListenerListData({ //方案修改和实施情况
           createMonth:this.month
        });
        const p8 = await getProgramTotal({ //当月施工方案电子审批数量对比
          month:this.month
        });
        const p9 = await getTechnicalCurrentMonthAbReport({ //当月施组、AB类施工方案报审通报信息
          queryMonth:this.month
        });
        const p10 = await getTechnicalCurrentMonthRollbackReport({ //当月施工方案回退通报（包括施组、ABCD方案）信息
          queryMonth:this.month
        });
        return Promise.all([p1, p2,p3,p4,p5,p6,p7,p8,p9,p10]).then(([res1, res2,res3,res4,res5,res6,res7,res8,res9,res10]) => {
          this.loading = false;
          this.monthProjectData = res1?.data || [];   
          this.nextMonthProjectData = res2?.data || [];      
          this.optimizeUnfinishedData = this.keyTwoArr(res3?.data,'branchComId').flat(Infinity)|| [];
          this.specificationData = res4?.data || []; 
          this.workArrangementData = res5?.data || [];
          //双优化总计
          //this.totalCountData = res6?.data?.totalCount;
          let totalCount = res6?.data?.totalCount || [],
          cloneAllTotalCountData = this.$clone(totalCount) || [],
          combinedTotalCountData = null;
          if(totalCount.length>0){
            combinedTotalCountData = [this.combinedFn(cloneAllTotalCountData)];
            this.totalCountData = [...totalCount,...combinedTotalCountData];
          }

          //this.detailCountData = res6?.data?.detailCount;
          let detailCount = res6?.data?.detailCount || [],
          newData = this.handlerDatas(this.$clone(detailCount)),
          newData1=null,newData2=null,newData3=null,combinedFnData=null;
          if(detailCount.length>0){
            newData1 = this.totalFn(newData);   // 新增小合计
            console.log(newData1,'newData1')
            newData2 = this.flattenArr(newData1,true); // 数组扁平化
            newData3 = this.$clone(newData2);
            combinedFnData = [this.combinedFn(newData2,'合计')];  //大合计
            combinedFnData[0].branchComId=null;  //必须设为null，不然出问题
            combinedFnData[0].planTime=null;  
            this.detailCountData = [...newData3,...combinedFnData];
          }

        
          let completeCount = res6?.data?.completeCount || [],
          cloneCompleteCountData = this.$clone(completeCount),
          combinedCompleteCountData =null;
          if(completeCount.length>0){
              combinedCompleteCountData = [this.combinedFn(cloneCompleteCountData)];
              this.completeCountData = [...completeCount,...combinedCompleteCountData];
          }

          //this.acceptanceCountData = res6?.data?.acceptanceCount; 
          
          let acceptanceCount = res6?.data?.acceptanceCount || [],
          cloneAcceptanceCountData = this.$clone(acceptanceCount),
          combinedAcceptanceCountData = null;
          if(acceptanceCount.length>0){
              combinedAcceptanceCountData = [this.combinedFn(cloneAcceptanceCountData)];
              this.acceptanceCountData = [...acceptanceCount,...combinedAcceptanceCountData];
          }
  
          this.planModifyData = this.keyTwoArr(res7?.data,'branchComId').flat(Infinity)|| [];
          this.approvalTableData = res8?.data || [];
          this.notificationTableData = res9?.data || [];
          this.fallbackTableData = res10?.data || [];
        })
      } catch (e) {
        this.loading = false; 
        return Promise.reject(e)
      }
    },

  }
}
</script>
<style lang="less" scoped>
.rollScroll{
  width: 100%;
  overflow-y:scroll;
}
.monthly-anchor{
  position: fixed;
  transition: all 0.3s;
  width:calc(100% - 328px);
  background-color: #fff;
  z-index: 1000;
  box-shadow: 3px 2px 20px #ebebeb;
  border: 1px solid #e8e8e8;
  margin-left: -10px;
  margin-top: -15px;
  .anchor-tab{
    display: inline-block;
    padding: 0 20px;
    line-height: 50px;
    cursor: pointer;
    p{
      padding: 0;
      margin: 0;
    }
   &.active{
     background-color: #387FC6;
     color: #fff;
   }
  }
  &.marginAnchor{
     top: 165px;
  }
}
.updateSummary-h3{
  line-height: 45px;
  width: 100%;
  text-align: center;
  background: rgb(244, 244, 244);
  border: 1px solid gainsboro;
  border-bottom: none;
  font-size: 14px;
  margin: 0;
}
</style>